var json_rpc2 = function(url, fn, jsonp_pre) {
	jsonp_pre = 'undefined' == typeof jsonp_pre ? 'jsonpcb' : jsonp_pre;
	
	var jsonpcb = 'json_rpc_' + (new Date()).getTime();
	eval(jsonpcb+" = function(d){ return fn(d); };");
	
	url += '&' + jsonp_pre + '=' + jsonpcb;
	
    var script = document.createElement("script");
    script.src = url;
    document.getElementById('json_rpc-root').appendChild(script);
};
var http_build_query = function  (formdata, numeric_prefix, arg_separator) {
    var value, key, tmp = [],
        that = this;

    var _http_build_query_helper = function (key, val, arg_separator) {
        var k, tmp = [];
        if (val === true) {
            val = "1";
        } else if (val === false) {
            val = "0";
        }
        if (val !== null && typeof(val) === "object") {
            for (k in val) {
                if (val[k] !== null) {
                    tmp.push(_http_build_query_helper(key + "[" + k + "]", val[k], arg_separator));
                }
            }
            return tmp.join(arg_separator);
        } else if (typeof(val) !== "function") {
            return encodeURIComponent(key) + "=" + encodeURIComponent(val);
        } else {
            throw new Error('There was an error processing for http_build_query().');
        }
    };

    if (!arg_separator) {
        arg_separator = "&";
    }
    for (key in formdata) {
        value = formdata[key];
        if (numeric_prefix && !isNaN(key)) {
            key = String(numeric_prefix) + key;
        }
        tmp.push(_http_build_query_helper(key, value, arg_separator));
    }

    return tmp.join(arg_separator);
};
function loadImage(url, _uid, callback) {
	var img = new Image();
	img.src = url;

	if (img.complete) {
		callback(img, _uid);
		return;
	}

	img.onload = function() { callback(img, _uid); };
};
/*
function loadUName(_uid, callback) {
	json_rpc2('http://graph.facebook.com/'+_uid+'?fields=id,name,picture', function(d){ // ,picture
		switch(true) {
		case typeof d.id == 'undefined': // 该用户无权限访问
		case typeof d.picture != 'undefined' && d.picture == 'http://static.ak.fbcdn.net/rsrc.php/v1/yo/r/UlIqmHJn-SK.gif':
			// TODO: 回报, 并删除该用户记录
			$.getJSON( endpoint.remove + '?jsonpcb=?', { 'uid': _uid });
			$('li[u='+_uid+']').remove();
			break;
		default:
			callback(_uid, d.name);
		}
	}, 'callback');
}
*/
function loadMoreData(l) {
	for(var i=0; i<=log_count; i++ ) {
		// 設置最後請求的uid
		json_rpc2('http://graph.facebook.com/' + l + '?fields=id,gender,locale,picture,name', function(d){
			if(
					typeof d.id != 'undefined' && 
					d.picture != 'http://profile.ak.fbcdn.net/static-ak/rsrc.php/v1/yo/r/UlIqmHJn-SK.gif' && 
					d.picture != 'http://profile.ak.fbcdn.net/static-ak/rsrc.php/v1/y9/r/IB7NOFmPw2a.gif'
			) {
				var qstr = http_build_query({
					'uid':			d.id,
					'gender':	d.gender,
					'locale':		d.locale,
					'picture':	d.picture,
					'name':		d.name
				});
				$.getJSON( endpoint.log + '?' + qstr + '&jsonpcb=?' );
			}
		}, 'callback');
		l++;
	}
}
function loadData(sex, loc, offset) {
	$('#resultBox').show();
	$('#loadingBar').show();
	$('#result').hide().html('');
	
	var p = {};
	p.loc			= loc;
	p.sex			= sex;
	p.offset		= offset;
	p.limit		= 10;
	
	$.getJSON( endpoint.query + '?jsonpcb=?', p,
	function(data) {
		console && console.log(data);
		
		if (typeof data.d == 'undefined') return false;

		$('#loadingBar').hide();
		$('#result').html('');
		if(data.d.length > 0) {
			for ( var i in data.d) {
				var u = data.d[i], uid = u.uid, html = [];
				
				html.push("<li u="+uid+"><img uicon_uid=" + uid + " src='public/loading-uicon.gif' />");
				html.push("<h5>" + u.nam + "</h5>");
				html.push("<a href='#@' u='"+uid+"' class='but01 btnAddF'>加为好友</a></li>");
				$('#result').append(html.join(''));
				
				loadImage(u.pic, uid, function(img, _uid){
					$('img[uicon_uid='+_uid+']').replaceWith(img);
				});
			}
			
			$('a.btnAddF').bind('click',function(){
				FB.ui({
					method: 'friends',
					id: $(this).attr('u')
			});
			});
		} else {
			$('#result').html('没有找到可以加好友的数据哦~, 再试试吧~');
		}
		

		/*
		var publish = {
				  method: 'friends',
				  id: 'brent',
				};

				FB.ui(publish);
		*/
		
		$('#result').show();
		loadMoreData(data.luid);

		Qing = false;
	});
}
